package com.securityMod.config;

import com.securityMod.entity.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author：kangsen
 * @Date：2022/10/25/0025 21:36
 * @Versiion：1.0
 * @Desc:
 */
@Component
public class CustomUserDetailService implements UserDetailsService {

    private static Map<String, UserInfo> map = new HashMap<>();

    static {
        map.put("admin", UserInfo.builder().id(1).userName("admin").address("陕西西安").password("123").role("admin").build());
        map.put("user", UserInfo.builder().id(1).userName("user").address("上海").password("123456").role("user").build());
        map.put("ks", UserInfo.builder().id(1).userName("ks").address("北京").password("123456").role("user").build());
        map.put("zhangsan", UserInfo.builder().id(1).userName("深圳").address("陕西西安").password("123456").role("user").build());
        map.put("lisi", UserInfo.builder().id(1).userName("lisi").address("成都").password("123456").role("user").build());
        map.put("wangwu", UserInfo.builder().id(1).userName("wangwu").address("重庆").password("123456").role("user").build());
    }

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        //通过userName获取用户信息
        UserInfo userInfo = map.get(userName);
        if(userInfo == null){
            throw new UsernameNotFoundException(userName + " not found ");
        }
        //定义权限列表
        List<GrantedAuthority> list = new ArrayList<>();
        //用户可以访问的资源名称 注意是要"ROLE_"开头
        list.add(new SimpleGrantedAuthority("ROLE_"+userInfo.getRole()));
        return new User(userInfo.getUserName(),passwordEncoder.encode(userInfo.getPassword()), list);
    }
}
